package com.tz.crm.utils;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;

import java.util.HashMap;
import java.util.Map;

/**
 * 错误信息封装工具
 */
public final class MsgErrorUtil {

    /**
     * 空参构造
     */
    private MsgErrorUtil() {
    }

    /**
     * 将参数错误信息封装到 map
     * key是参数名，value是错误提示信息
     *
     * @param bindingResult BindingResult
     * @return 错误信息map
     */
    public static Map<String, String> getErrorMap(BindingResult bindingResult) {
        Map<String, String> errorMap = new HashMap<>();
        for (ObjectError objectError : bindingResult.getAllErrors()) {
            FieldError fieldError = (FieldError) objectError;
            String field = fieldError.getField();
            String error = fieldError.getDefaultMessage();
            errorMap.put(field, error);
        }
        return errorMap;
    }

}
